/**
 * 通用js方法封装处理
 * Copyright (c) 2022 lanqing
 */
import {login} from "@/api/login";
import {encrypt} from "@/utils/jsencrypt";
import {setToken} from "@/utils/auth";


// 日期格式化
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}
//日期格式化
export function formatDate(vals){
  var time = new Date(vals);
  var year = time.getFullYear();
  var month = time.getMonth() + 1;
  var date = time.getDate();
  function add0(m) {
    return m < 10 ? "0" + m : m;
  }
  var startTime = add0(year) + "-" + add0(month) + "-" + add0(date);
  return startTime;
}
// 表单重置
export function resetForm(refName) {
  if (this.$refs[refName]) {
    this.$refs[refName].resetFields();
  }
}

// 添加日期范围
export function addDateRange(params, timeData, propName) {
  let search = params;
  search.params = typeof (search.params) === 'object' && search.params !== null && !Array.isArray(search.params) ? search.params : {};
  timeData = Array.isArray(timeData) ? timeData : [];
  if (typeof (propName) === 'undefined') {
    search.params['beginTime'] = timeData[0];
    search.params['endTime'] = timeData[1];
  } else {
    search.params['begin' + propName] = timeData[0];
    search.params['end' + propName] = timeData[1];
  }
  return search;
}

// 回显数据字典
export function selectDictLabel(datas, value) {
  if (value === undefined) {
    return "";
  }
  const actions = [];
  Object.keys(datas).some((key) => {
    if (datas[key].value == ('' + value)) {
      actions.push(datas[key].label);
      return true;
    }
  })
  if (actions.length === 0) {
    actions.push(value);
  }
  return actions.join('');
}

// 回显数据字典（字符串数组）
export function selectDictLabels(datas, value, separator) {
  if (value === undefined) {
    return "";
  }
  const actions = [];
  const currentSeparator = undefined === separator ? "," : separator;
  const temp = value.split(currentSeparator);
  Object.keys(value.split(currentSeparator)).some((val) => {
    let match = false;
    Object.keys(datas).some((key) => {
      if (datas[key].value == ('' + temp[val])) {
        actions.push(datas[key].label + currentSeparator);
        match = true;
      }
    })
    if (!match) {
      actions.push(temp[val] + currentSeparator);
    }
  })
  return actions.join('').substring(0, actions.join('').length - 1);
}

// 字符串格式化(%s )
export function sprintf(str) {
  let args = arguments, flag = true, i = 1;
  str = str.replace(/%s/g, function () {
    const arg = args[i++];
    if (typeof arg === 'undefined') {
      flag = false;
      return '';
    }
    return arg;
  });
  return flag ? str : '';
}

// 转换字符串，undefined,null等转化为""
export function parseStrEmpty(str) {
  if (!str || str == "undefined" || str == "null") {
    return "";
  }
  return str;
}

// 数据合并
export function mergeRecursive(source, target) {
  for (var p in target) {
    try {
      if (target[p].constructor == Object) {
        source[p] = mergeRecursive(source[p], target[p]);
      } else {
        source[p] = target[p];
      }
    } catch (e) {
      source[p] = target[p];
    }
  }
  return source;
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree(data, id, parentId, children) {
  let config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: children || 'children'
  };

  const childrenListMap = {};
  const nodeIds = {};
  const tree = [];

  for (let d of data) {
    let parentId = d[config.parentId];
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = [];
    }
    nodeIds[d[config.id]] = d;
    childrenListMap[parentId].push(d);
  }

  for (let d of data) {
    let parentId = d[config.parentId];
    if (nodeIds[parentId] == null) {
      tree.push(d);
    }
  }

  for (let t of tree) {
    adaptToChildrenList(t);
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]];
    }
    if (o[config.childrenList]) {
      for (let c of o[config.childrenList]) {
        adaptToChildrenList(c);
      }
    }
  }
  return tree;
}

/**
 * 参数处理
 * @param {*} params  参数
 */
export function tansParams(params) {
  let result = ''
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    const part = encodeURIComponent(propName) + "=";
    if (value !== null && value !== "" && typeof (value) !== "undefined") {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== 'undefined') {
            let params = propName + '[' + key + ']';
            var subPart = encodeURIComponent(params) + "=";
            result += subPart + encodeURIComponent(value[key]) + "&";
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&";
      }
    }
  }
  return result
}



// 返回项目路径
export function getNormalPath(p) {
  if (p.length === 0 || !p || p == 'undefined') {
    return p
  }
  let res = p.replace('//', '/')
  if (res[res.length - 1] === '/') {
    return res.slice(0, res.length - 1)
  }
  return res;
}

// 验证是否为blob格式
export async function blobValidate(data) {
  try {
    const text = await data.text();
    JSON.parse(text);
    return false;
  } catch (error) {
    return true;
  }
}

//根据字典反label无value
export function returnDictLabel(dictObj, value) {
  if (value ||value ===0) {
    let obj = dictObj.filter(item => {
      //用 == 是因为有可能类型不一样
      return item.value == value
    })
    if(obj.length>0){
      return  obj[0].label
    }
    return ""
  } else {
    return ""
  }
}
//根据字典反label无value (多个字典值)
export function returnDictLabels(dictObj, value) {
  if (value||value ===0) {
    let ids =value.split(",")
    let labels =[];
    for (let i = 0; i <ids.length ; i++) {
      let obj = dictObj.filter(item => {
        return item.value == ids[i]
      })
      if(obj.length>0){
        labels.push(obj[0].label ||  obj[0].text)
      }
    }

    return labels.join(",")
  } else {
    return ""
  }
}

//根据字典label 返回 value
export function returnDictValue(dictObj, label) {
  if (label) {
    let obj = dictObj.filter(item => {
      return item.label === label
    })
    return obj[0].value
  } else {
    return ""
  }
}

//获取当前日期
export  function getTodayData(){
  // 获取当前日期
  var date = new Date();
// 获取当前月份
  var nowMonth = date.getMonth() + 1;
// 获取当前是几号
  var strDate = date.getDate();
// 添加分隔符“-”
  var seperator = "";
// 对月份进行处理，1-9月在前面添加一个“0”
  if (nowMonth >= 1 && nowMonth <= 9) {
    nowMonth = "0" + nowMonth;
  }
// 对月份进行处理，1-9号在前面添加一个“0”
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
// 最后拼接字符串，得到一个格式为(yyyy-MM-dd)的日期
  var nowDate = date.getFullYear()+"-" + seperator + nowMonth +"-"+ seperator + strDate;
  return nowDate
}
//获取当前日期星期 时分秒
export function getHere(){
  var date = new Date();
  var year = date.getFullYear() // 年
  var nowMonth = date.getMonth() + 1;
  var strDate = date.getDate();
  let weeks = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
  var week=weeks[date.getDay()]
  var hour = date.getHours(); // 时
  var minutes = date.getMinutes(); // 分
  var seconds = date.getSeconds() //秒
  if (hour >= 0 && hour <= 9) {
    hour = "0" + hour;
  }
  if (minutes >= 0 && minutes <= 9) {
    minutes = "0" + minutes;
  }
  if (seconds >= 0 && seconds <= 9) {
    seconds = "0" + seconds;
  }
  return year+'年'+nowMonth+'月'+strDate+'日'+'    '+week+'    '+hour+':'+minutes+':'+seconds
}

//获取当前月份
export  function getMonthData(){
  // 获取当前日期
  var date = new Date();
// 获取当前月份
  var nowMonth = date.getMonth() + 1;
// 获取当前是几号
  var strDate = date.getDate();
// 添加分隔符“-”
  var seperator = "";
// 对月份进行处理，1-9月在前面添加一个“0”
  if (nowMonth >= 1 && nowMonth <= 9) {
    nowMonth = "0" + nowMonth;
  }
// 对月份进行处理，1-9号在前面添加一个“0”
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
// 最后拼接字符串，得到一个格式为(yyyy-MM)的日期
  var nowDate = date.getFullYear()+"-" + seperator + nowMonth;
  return nowDate
}

// 获取当前日期的前一天
export  function getDayBefore(){
  // 获取前一天
  var date = new Date(new Date().getTime() - 24 * 60 * 60 * 1000);
// 获取当前月份
  var nowMonth = date.getMonth() + 1;
// 获取当前是几号
  var strDate = date.getDate();
// 添加分隔符“-”
  var seperator = "";
// 对月份进行处理，1-9月在前面添加一个“0”
  if (nowMonth >= 1 && nowMonth <= 9) {
    nowMonth = "0" + nowMonth;
  }
// 对月份进行处理，1-9号在前面添加一个“0”
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
// 最后拼接字符串，得到一个格式为(yyyy-MM-dd)的日期
  var nowDate = date.getFullYear()+"-" + seperator + nowMonth +"-"+ seperator + strDate;
  return nowDate
}

// 获取指定日期的前三天
export  function getCustomDayBefore(time){
  // 获取前一天
  var date = new Date(time - 24*3 * 60 * 60 * 1000);
// 获取当前月份
  var nowMonth = date.getMonth() + 1;
// 获取当前是几号
  var strDate = date.getDate();
// 添加分隔符“-”
  var seperator = "";
// 对月份进行处理，1-9月在前面添加一个“0”
  if (nowMonth >= 1 && nowMonth <= 9) {
    nowMonth = "0" + nowMonth;
  }
// 对月份进行处理，1-9号在前面添加一个“0”
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
// 最后拼接字符串，得到一个格式为(yyyy-MM-dd)的日期
  var nowDate = date.getFullYear()+"-" + seperator + nowMonth +"-"+ seperator + strDate;
  return nowDate
}

//获取本周是第几周
export function getYearWeek(){
  let temptTime = new Date();
  let weekday = temptTime.getDay() & 7;
  temptTime.setDate(temptTime.getDate() - weekday + 1 + 5);
  let firstDay = new Date(temptTime.getFullYear(), 0, 1);
  let dayOfWeek = firstDay.getDay();
  let spendDay = 1;
  if (dayOfWeek != 0) {
    spendDay = 7 - dayOfWeek + 1;
  }
  let yearOfW = temptTime.getFullYear();
  firstDay = new Date(yearOfW, 0, 1 + spendDay);
  let d = Math.ceil((temptTime.valueOf() - firstDay.valueOf()) / 86400000);
  let res = Math.ceil(d / 7);
  if(weekday ===0){
    //星期天就减一周
    res= res-1;
  }
  return res
}

/*
*
指定日期的开始时间 结束时间 (n:当前日期减几天)
本周的开始时间
console.log(getTimeByDay(0));
本周的结束时间
console.log(getTimeByDay(-6));
下周的开始时间
console.log(getTimeByDay(-7));
下周结束时间
console.log(getTimeByDay(-13));
*/
export function getTimeByDay(n) {
  var now = new Date();
  var year = now.getFullYear();
  //因为月份是从0开始的,所以获取这个月的月份数要加1才行
  var month = now.getMonth() + 1;
  var date = now.getDate();
  var day = now.getDay();

  //判断是否为周日,如果不是的话,就让今天的day-1(例如星期二就是2-1)
  if (day !== 0) {
    n = n + (day - 1);
  } else {
    n = n + day;
  }
  if (day) {
    //这个判断是为了解决跨年的问题
    if (month > 1) {
      month = month;
    }
    //这个判断是为了解决跨年的问题,月份是从0开始的
    else {
      year = year - 1;
      month = 12;
    }
  }
  now.setDate(now.getDate() - n);
  month = now.getMonth() + 1;
  date = now.getDate();
  var s = year + "-" + (month < 10 ? ('0' + month) : month) + "-" + (date < 10 ? ('0' + date) : date);
  return s;
}

//获取指定日期是当年的第几周
export function getWeekByTime(dt){
  let d1 = new Date(dt);
  let d2 = new Date(dt);
  d2.setMonth(0);
  d2.setDate(1);
  let rq = d1-d2;
  let days = Math.ceil(rq/(24*60*60*1000));
  let num = Math.ceil(days/7);
  return num;
}

//获取近一周时间
export function getWeek(){
  var end = new Date();
  var year = end.getFullYear();
  var month = end.getMonth() + 1;//0-11表示1-12月
  var day = end.getDate();
  var dateObj = {};
  if (day - 7 <= 0) {   //如果在当月7日之前
    var startMonthDay = new Date(year, (parseInt(month) - 1), 0).getDate();    //1周前所在月的总天数
    if (month - 1 <= 0) { //如果在当年的1月份
      dateObj.start = (year - 1) + '-' + 12 + '-' + ((31 - (7 - day))>=10?(31 - (7 - day)):'0'+(31 - (7 - day)));
    } else {
      dateObj.start = year + '-' + ((month - 1)>=10?(month - 1):'0'+(month - 1)) + '-' + ((startMonthDay - (7 - day))>=10?(startMonthDay - (7 - day)):'0'+(startMonthDay - (7 - day)));
    }
  } else {
    dateObj.start = year + '-' + (month>=10?month:'0'+month) + '-' + ((day - 7)>=10?(day - 7):'0'+(day - 7));
  }
  dateObj.end = year + '-' + (month>=10?month:'0'+month) + '-' + (day>=10?day:'0'+day);
  return dateObj
}

//获取近一月
export function getOneMonth(){
  var end = new Date();
  var year = end.getFullYear();
  var month = end.getMonth() + 1;//0-11表示1-12月
  var day = end.getDate();
  var dateObj = {};
  var endMonthDay = new Date(year, month, 0).getDate();    //当前月的总天数
  if(month - 1 <= 0){ //如果是1月，年数往前推一年<br>　　　　
    dateObj.start = (year - 1) + '-' + 12 + '-' + (day>=10?day:'0'+day);
  }else{
    var startMonthDay = new Date(year, (parseInt(month) - 1), 0).getDate();
    if(startMonthDay < day){    //1个月前所在月的总天数小于现在的天日期
      if(day < endMonthDay){        //当前天日期小于当前月总天数
        dateObj.start = year + '-' + (month>=10?month - 1:'0'+(month-1)) + '-' + (startMonthDay - (endMonthDay - day)>=10?startMonthDay - (endMonthDay - day):'0'+(startMonthDay - (endMonthDay - day)));
      }else{
        dateObj.start = year + '-' + (month>=10?month - 1:'0'+(month-1)) + '-' + (startMonthDay>=10?startMonthDay:'0'+startMonthDay);
      }
    }else{
      dateObj.start = year + '-' + (month>=10?month - 1:'0'+(month-1)) + '-' + (day>=10?day:'0'+day);
    }
  }
  dateObj.end = year + '-' + (month>=10?month:'0'+month) + '-' + (day>=10?day:'0'+day);
  return dateObj
}
//获取近半年日期
export function halfYear(){
  var end = new Date();
  var year = end.getFullYear();
  var month = end.getMonth() + 1;//0-11表示1-12月
  var day = end.getDate();
  var dateObj = {};
  var endMonthDay = new Date(year, month, 0).getDate();    //当前月的总天数
  if(month - 6 <= 0){ //如果是1、2、3月，年数往前推一年
    var start6MonthDay = new Date((year - 1), (12 - (6 - parseInt(month))), 0).getDate();    //6个月前所在月的总天数
    if(start6MonthDay < day){    //3个月前所在月的总天数小于现在的天日期
      dateObj.start = (year - 1) + '-' + ((12 - (6 - month))>=10?(12 - (6 - month)):'0'+(12 - (6 - month))) + '-' + (start6MonthDay>=10?start6MonthDay:'0'+start6MonthDay);
    }else{
      dateObj.start = (year - 1) + '-' + ((12 - (6 - month))>=10?(12 - (6 - month)):'0'+(12 - (6 - month))) + '-' + (day>=10?day:'0'+day);
    }
  }else{
    var start6MonthDay = new Date(year, (parseInt(month) - 6), 0).getDate();    //6个月前所在月的总天数
    if(start6MonthDay < day){    //6个月前所在月的总天数小于现在的天日期
      if(day < endMonthDay){        //当前天日期小于当前月总天数,2月份比较特殊的月份
        dateObj.start = year + '-' + ((month - 6)>=10?(month - 6):'0'+(month - 6)) + '-' + ((start6MonthDay - (endMonthDay - day))>=10?(start6MonthDay - (endMonthDay - day)):'0'+(start6MonthDay - (endMonthDay - day)));
      }else{
        dateObj.start = year + '-' + ((month - 6)>=10?(month - 6):'0'+(month - 6)) + '-' + (start6MonthDay>=10?start6MonthDay:'0'+start6MonthDay);
      }
    }else{
      dateObj.start = year + '-' + ((month - 6)>=10?(month - 6):'0'+(month - 6)) + '-' + (day>=10?day:'0'+day);
    }
  }
  dateObj.end = year + '-' +  (month>=10?month:'0'+month) + '-' +  (day>=10?day:'0'+day);
  return dateObj
}

//获取本年日期 //type为字符串类型，有两种选择，"s"代表开始,"e"代表结束，dates为数字类型，不传或0代表今年，-1代表去年，1代表明年
export function getSelectYear(type, dates) {
  var dd = new Date();
  var n = dates || 0;
  var year = dd.getFullYear() + Number(n);
  if (type == "s") {
    var day = year + "-01-01";
  }
  if (type == "e") {
    var day = year + "-12-31";
  }
  if (!type) {
    var day = year + "-01-01/" + year + "-12-31";
  }
  return day + ' 00:00:00';
}
//获取近n年日期 val一年的天数
export function getOneYear(val){
  var nowDate = new Date();
  var date = new Date(nowDate);
  date.setDate(date.getDate()-val);
  var seperator1 = "-";
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  var currentdate = year + seperator1 + month + seperator1 + strDate;
  return currentdate;
}

//获取当前小时分钟
export function getHourMinutes(){
  var data = new Date()
  var hour = data.getHours() <= 0 ?'0'+data.getHours() : data.getHours()
  var minutes = data.getMinutes()<= 10 ?'0'+data.getMinutes() : data.getMinutes()
  var time = hour+':'+minutes
  return time
}
// 获取当前日期时分秒
export function getNowDate(){
  var date = new Date();
  var sign2 = ":";
  var year = date.getFullYear() // 年
  var month = date.getMonth() + 1; // 月
  var day = date.getDate(); // 日
  var hour = date.getHours(); // 时
  var minutes = date.getMinutes(); // 分
  var seconds = date.getSeconds() //秒
  var weekArr = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天'];
  var week = weekArr[date.getDay()];
  // 给一位数的数据前面加 “0”
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (day >= 0 && day <= 9) {
    day = "0" + day;
  }
  if (hour >= 0 && hour <= 9) {
    hour = "0" + hour;
  }
  if (minutes >= 0 && minutes <= 9) {
    minutes = "0" + minutes;
  }
  if (seconds >= 0 && seconds <= 9) {
    seconds = "0" + seconds;
  }
  return year + "-" + month + "-" + day + " " + hour + sign2 + minutes + sign2 + seconds;
}
// 获取当前日期时分
export function getSunTimeDivide(){
  var date = new Date();
  var sign2 = ":";
  var year = date.getFullYear() // 年
  var month = date.getMonth() + 1; // 月
  var day = date.getDate(); // 日
  var hour = date.getHours(); // 时
  var minutes = date.getMinutes(); // 分
  var weekArr = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天'];
  var week = weekArr[date.getDay()];
  // 给一位数的数据前面加 “0”
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (day >= 0 && day <= 9) {
    day = "0" + day;
  }
  if (hour >= 0 && hour <= 9) {
    hour = "0" + hour;
  }
  if (minutes >= 0 && minutes <= 9) {
    minutes = "0" + minutes;
  }
  return year + "-" + month + "-" + day + " " + hour + sign2 + minutes ;
}

//获取当前月 第一天
export function getNowMonthFirst(){
  const date = new Date()
  date.setDate(1)
  return getTimeToString(date)
}
//获取当前月 最后一天
export function getNowMonthLast (){
  const date = new Date()
  const enddate = new Date(date.getFullYear(), date.getMonth() + 1, 0)
  return getTimeToString(enddate)
}
//把年月日时分秒 转成时分
export function toHour(timeStr) {
  return timeStr.substring(timeStr.indexOf(" "), timeStr.length - 3).trim()
}


//时间戳转字符串 年月日
export function getTimeToString(time){
  const date = new Date(time)
  const Y = date.getFullYear()
  const M = date.getMonth() + 1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1
  const D = date.getDate() <10 ?'0'+date.getDate():date.getDate()
  return `${Y}-${M}-${D}`
}
//时间戳转字符串 年月日 时分秒
export function getTimeToHms(time) {
  const date = new Date(time)
  const Y = date.getFullYear()
  const M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  const D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  const Hh = date.getHours()< 10 ? '0' + date.getHours() : date.getHours()
  const mm = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
  const ss = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
  return `${Y}-${M}-${D} ${Hh}:${mm}:${ss}`
}
//计算距传入天数的日期 today为日期 many为天数
export function dateArea(many,today) {
  let data = new Date(today)
  let date = data.toLocaleDateString()
  let time = data.getTime()
  let arr = date.split('/').map(item=> {
    if (item.length>2) return item
    const str = item.length>1?item:('0'+item)
    return str
  })
  time = time-(24*60*60*1000*many)
  let art = new Date(time)
  let datetr = art.toLocaleDateString()
  let arrtr = datetr.split('/').map(item=> {
    if (item.length>2) return item
    const str = item.length>1?item:('0'+item)
    return str
  })
  // 今天
  date = arr.join('-')
  // many天前
  datetr = arrtr.join('-')
  return datetr
}
//获取当前月一整月数据
export function getCurrentMonth(){
  //本月第一天
  function showFirstDay()
  {
    var Nowdate=new Date();
    var MonthFirstDay=new Date(Nowdate.getYear(),Nowdate.getMonth(),1).getDate();
    return MonthFirstDay;
  }
  //本月最后一天
  function showLastDay()
  {
    var Nowdate=new Date();
    var tmpDate=new Date(Nowdate.getYear(),Nowdate.getMonth()+1,1);
    var MonthLastDay=new Date(tmpDate-86400000).getDate();
    return MonthLastDay;
  }
  var last = showLastDay();
  var start = showFirstDay();
  var date = new Date();
  var a = [];
  for(var i=start;i<=last;i++){
    a[i-1] = date.getFullYear()+"-"+((date.getMonth()+1)<10?'0'+(date.getMonth()+1):(date.getMonth()+1))+"-"+(i<10?'0'+i:i);
  }
  var res = {
    start:a[0],
    end:a[a.length-1]
  }
  return res;
}

//获取指定年月一整月数据
export function getCurrentCustomMonth(year,month){
  //本月第一天
  function showFirstDay()
  {
    var MonthFirstDay=new Date(year,month-1,1).getDate();
    return MonthFirstDay;
  }
  //本月最后一天
  function showLastDay()
  {
    var tmpDate=new Date(year,month,1);
    var MonthLastDay=new Date(tmpDate-86400000).getDate();
    return MonthLastDay;
  }
  var last = showLastDay();
  var start = showFirstDay();

  var a = [];
  for(var i=start;i<=last;i++){
    a[i-1] = year+"-"+((month*1)<10?'0'+(month*1):(month*1))+"-"+(i<10?'0'+i:i);
  }
  var res = {
    start:a[0],
    end:a[a.length-1]
  }
  return res;
}

//获取上月第一天与最后一天
export function getUpMonth(){
  //本月第一天
  function showFirstDay()
  {
    var Nowdate=new Date();
    var MonthFirstDay=new Date(Nowdate.getFullYear(), Nowdate.getMonth() - 1, 1);
    return MonthFirstDay;
  }
  //本月最后一天
  function showLastDay()
  {
    var Nowdate=new Date();
    var tmpDate=new Date(Nowdate.getFullYear(), Nowdate.getMonth(), 0).getDate()
    var MonthLastDay=new Date(Nowdate.getFullYear(), Nowdate.getMonth() - 1, tmpDate)
    return MonthLastDay;
  }
  var last = formatDate(showLastDay());
  var start = formatDate(showFirstDay());
  let res={start:start,end:last}
  return res
}
//获取本周上周开始结束时间
//上周的开始时间
// console.log(getWeekTime(7));
//上周的结束时间
// console.log(getWeekTime(1));
//本周的开始时间
// console.log(getWeekTime(0));
//本周的结束时间
// console.log(getWeekTime(-6));
export function getWeekTime(n){
  var now=new Date();
  var year=now.getFullYear();
  //因为月份是从0开始的,所以获取这个月的月份数要加1才行
  var month=now.getMonth()+1;
  var date=now.getDate();
  var day=now.getDay();
  // console.log(date);
  //判断是否为周日,如果不是的话,就让今天的day-1(例如星期二就是2-1)
  if(day!==0){
    n=n+(day-1);
  }
  else{
    n=n+day;
  }
  if(day){
    //这个判断是为了解决跨年的问题
    if(month>1){
      month=month;
    }
    //这个判断是为了解决跨年的问题,月份是从0开始的
    else{
      year=year-1;
      month=12;
    }
  }
  now.setDate(now.getDate()-n);
  year=now.getFullYear();
  month=now.getMonth()+1;
  date=now.getDate();
  // console.log(n);
  var s=year+"-"+(month<10?('0'+month):month)+"-"+(date<10?('0'+date):date);
  return s;
}
//季度获取
export function getQuarterMonth(type) {
  var now = new Date();
  var nowMonth = now.getMonth();
  var year = now.getFullYear();
  var quarterStartMonth = 1;
  if (nowMonth < 3) {
    quarterStartMonth = 1;
  }
  if (2 < nowMonth && nowMonth < 6) {
    quarterStartMonth = 4;
  }
  if (5 < nowMonth && nowMonth < 9) {
    quarterStartMonth = 7;
  }
  if (nowMonth > 8) {
    quarterStartMonth = 10;
  }
  if (type == "s") {
    var day = year + "-" + quarterStartMonth + "-01";
  } //1-3 4-6 7-9 10-12
  if (type == "e") {
    if (quarterStartMonth == 1) {
      var day = year + "-" + (quarterStartMonth + 2) + "-31";
    }
    if (quarterStartMonth == 10) {
      var day = year + "-" + (quarterStartMonth + 2) + "-31";
    }
    if (quarterStartMonth == 4) {
      var day = year + "-" + (quarterStartMonth + 2) + "-30";
    }
    if (quarterStartMonth == 7) {
      var day = year + "-" + (quarterStartMonth + 2) + "-30";
    }
  }
  return day;
}
//获取本季度开始结束日期
export function getThisQuarter(){
  let s = formatDate(getQuarterMonth("s"));
  let e = formatDate(getQuarterMonth("e"));
  let timerValue = {start:s,end:e}
  return timerValue
}
//年度获取
export function getYear(type, dates) {
  var dd = new Date();
  var n = dates || 0;
  var year = dd.getFullYear() + Number(n);
  if (type == "s") {
    var day = year + "-01-01";
  }
  if (type == "e") {
    var day = year + "-12-31";
  }
  if (!type) {
    var day = year + "-01-01/" + year + "-12-31";
  }
  return day;
}
//获取去年开始结束时间
export function getLastYear(){
  let s = getYear("s", -1);
  let e = getYear("e", -1);
  let timerValue = {start:s,end:e}
  return timerValue

}
//获取当前年月
export function getDays(){
  const date = new Date()
  const Y = date.getFullYear()
  const M = date.getMonth() + 1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1
  return `${Y}-${M}`
}
//获取当前年
export function getNowYear(){
  const date = new Date()
  const Y = date.getFullYear()
  return Y+''
}
//计算传入日期距当前年月
export function getYearMonthDiff(dateString) {
  const currentDate = new Date(); // 获取当前日期对象
  const targetDate = new Date(dateString); // 将目标日期字符串转换为日期对象
  let diffYears = currentDate.getFullYear() - targetDate.getFullYear(); // 计算相隔的年份
  let diffMonths = currentDate.getMonth() - targetDate.getMonth(); // 计算相隔的月份，初始值为两个月份之间的差

  if (diffMonths < 0) { // 如果相隔的月份为负数，则需要加上12个月
    diffMonths += 12;
    diffYears--; // 相隔的年份也需要减1
  }

  return [diffYears, diffMonths];
}
//获取下周的开始日期和结束日期
export function getNextWeek() {
  const currentDate = new Date();
  const oneDay = 24 * 60 * 60 * 1000;
  const currentWeekday = currentDate.getDay();

  const firstDayOfNextWeek = new Date(currentDate.getTime() + (8 - currentWeekday) * oneDay);
  const lastDayOfWeek = new Date(currentDate.getTime() + (14 - currentWeekday) * oneDay);

  const startYear = firstDayOfNextWeek.getFullYear();
  const startMonth = (firstDayOfNextWeek.getMonth() + 1).toString().padStart(2, '0');
  const startDay = firstDayOfNextWeek.getDate().toString().padStart(2, '0');

  const endYear = lastDayOfWeek.getFullYear();
  const endMonth = (lastDayOfWeek.getMonth() + 1).toString().padStart(2, '0');
  const endDay = lastDayOfWeek.getDate().toString().padStart(2, '0');

  return {
    start: `${startYear}-${startMonth}-${startDay}`,
    end: `${endYear}-${endMonth}-${endDay}`
  };
}
//获取下月
export function getNextMonth() {
  const currentDate = new Date();
  const firstDayOfNextMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 1);
  const lastDayOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 1);

  lastDayOfMonth.setMonth(lastDayOfMonth.getMonth() + 1);
  lastDayOfMonth.setDate(lastDayOfMonth.getDate() - 1);

  const startYear = firstDayOfNextMonth.getFullYear();
  const startMonth = (firstDayOfNextMonth.getMonth() + 1).toString().padStart(2, '0');
  const startDay = firstDayOfNextMonth.getDate().toString().padStart(2, '0');

  const endYear = lastDayOfMonth.getFullYear();
  const endMonth = (lastDayOfMonth.getMonth() + 1).toString().padStart(2, '0');
  const endDay = lastDayOfMonth.getDate().toString().padStart(2, '0');
  return {
    start: `${startYear}-${startMonth}-${startDay}`,
    end: `${endYear}-${endMonth}-${endDay}`
  };
}

//base64转文件方法
export function base64toFile(dataurl, filename = 'file') {
  let arr = dataurl.split(',');
  let mime = arr[0].match(/:(.*?);/)[1];
  // suffix是该文件的后缀
  let suffix = mime.split('/')[1];
  // atob 对经过 base-64 编码的字符串进行解码
  let bstr = atob(arr[1]);
  // n 是解码后的长度
  let n = bstr.length;
  // Uint8Array 数组类型表示一个 8 位无符号整型数组 初始值都是 数子0
  let u8arr = new Uint8Array(n);
  // charCodeAt() 方法可返回指定位置的字符的 Unicode 编码。这个返回值是 0 - 65535 之间的整数
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  // new File返回File对象 第一个参数是 ArraryBuffer 或 Bolb 或Arrary 第二个参数是文件名
  // 第三个参数是 要放到文件中的内容的 MIME 类型
  return new File([u8arr], `${filename}.${suffix}`, {
    type: mime,
  });
}
//判断是否为对象数据类型
export function isObject(value) {
  return typeof value === "object" && Object.prototype.toString.call(value) === "[object Object]";
}
/**
 * 压缩图片
 */
export function compressImage (file,width,height) {

  const read = new FileReader()
  read.readAsDataURL(file)
  return new Promise(function (resolve, reject) {
    read.onload = function (e) {
      let img = new Image()
      img.src = e.target.result
      img.onload = function () {
        // 默认按比例压缩
        let w =width|| 450
        let h =height|| 500
        // 生成canvas
        let canvas = document.createElement('canvas')
        let ctx = canvas.getContext('2d')
        let base64
        // 创建属性节点
        canvas.setAttribute('width', w)
        canvas.setAttribute('height', h)
        ctx.drawImage(this, 0, 0, w, h)
        base64 = canvas.toDataURL(file['type'], 0.9)
        resolve(base64)
      }
    }
  })
}

//医保创建script

export function myjsonp(URL, callback, callbackname) {
  //给系统中创建一个全局变量，叫做callbackname，指向callback函数
  //定义
  window[callbackname] = function (data) {
    callback(data)
    //为了不污染页面，把script拿掉
    document.head.removeChild(oscript);
  }
  //创建一个script节点
  var oscript = document.createElement("script");
  //和image不一样，设置src并不会发出HTTP请求
  oscript.src = URL;
  oscript.type = "text/javascript";
  //script标签的请求是在上树的时候发出，请求的是一个函数的执行语句
  document.head.appendChild(oscript);
}
export function getRequest(url,params){
  return new Promise((resolve, reject) => {
    myjsonp(import.meta.env.VITE_APP_API_YB+url+disposeParams(params),
        function (data) {
          let utf8EncodedString = atob(data.data); // 解码Base64编码字符串为UTF-8编码字符串
          let chineseString = decodeURIComponent(Array.prototype.map.call(utf8EncodedString, function (c) {
            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
          }).join('')); // 将UTF-8编码字符串还原为中文字符串
          resolve(chineseString)
        }, "showInfo")
  })

}
export function disposeParams(obj) {
  let result = '';
  let item;
  for (item in obj) {
    if (obj[item] && String(obj[item])) {
      result += `&${item}=${obj[item]}`;
    }
  }
  if (result) {
    result = '?' + result.slice(1);
  }
  return result;
}
//获取图片的地址的宽高
export function datadragEnd (url){
  // 创建实例对象
  return new Promise((resolve, reject) => {
    var img = new Image();
    // 图片地址
    img.src = url;
    let res = {}
    img.onload = function () {
      res = {
        width: img.width,
        height: img.height
      }
      resolve(res)
    }
  })

}
//金额格式化大写
export function toChies(money) {
  const cnNums = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
  const cnIntRadice = ['', '拾', '佰', '仟'];
  const cnIntUnits = ['', '万', '亿', '兆'];
  const cnDecUnits = ['角', '分', '毫', '厘'];
  const cnInteger = '整';
  const cnIntLast = '元';
  const maxNum = 999999999999999.9999;

  if (!money) {
    return '';
  }

  money = parseFloat(money);
  if (money >= maxNum) {
    return '';
  }

  if (money === 0) {
    return cnNums[0] + cnIntLast + cnInteger;
  }

  money = money.toString();
  let [integerNum, decimalNum] = money.split('.');

  let chineseStr = '';
  if (parseInt(integerNum, 10) > 0) {
    let zeroCount = 0;
    const IntLen = integerNum.length;
    for (let i = 0; i < IntLen; i++) {
      const n = parseInt(integerNum.charAt(i));
      const p = IntLen - i - 1;
      const q = Math.floor(p / 4);
      const m = p % 4;
      if (n === 0) {
        zeroCount++;
      } else {
        if (zeroCount > 0) {
          chineseStr += cnNums[0];
        }
        zeroCount = 0;
        chineseStr += cnNums[n] + cnIntRadice[m];
      }
      if (m === 0 && zeroCount < 4) {
        chineseStr += cnIntUnits[q];
      }
    }
    chineseStr += cnIntLast;
  }

  if (decimalNum) {
    const decLen = decimalNum.length;
    for (let i = 0; i < decLen; i++) {
      const n = parseInt(decimalNum.charAt(i));
      if (n !== 0) {
        chineseStr += cnNums[n] + cnDecUnits[i];
      }
    }
  } else if (!chineseStr) {
    chineseStr += cnInteger;
  }

  return chineseStr;
}

/**
 * 防抖函数
 * 防抖原理：一定时间内，只有最后一次操作，再过wait毫秒后才执行函数
 *
 * @param {Function} func 要执行的回调函数
 * @param {Number} wait 延时的时间
 * @return null
 */
let timeout = null;

export function debounceTime(func, wait) {

  let args = arguments;
  let that = this;
  // 清除上一次延时器
  clearTimeout(timeout)
  timeout = setTimeout(function () {
    func.apply(that, args)
  }, wait|| 500);

}
//获取当前时间前面第三天的日期
export function getThreeDay(){
  const today = new Date(); // 获取当前时间
  const threeDaysAgo = new Date(today); // 创建一个新的日期对象，初始值为当前时间
  threeDaysAgo.setDate(today.getDate() - 2); // 将日期设置为当前时间的前面第三天
  return threeDaysAgo.toISOString().split('T')[0] // 输出前面第三天的日期，格式为YYYY-MM-DD
}


//只能输入正数 2位小数
export function limitNumber(val) {
  if(val){
    //替换掉数字和小数点 . 之外的字符
    val = val.replace(/[^\d.]/g,"");
    //把2个以上的小数点 . 替换成一个小数点 .
    val = val.replace(/\.{2,}/g,".");
    //保证第一个字符为数字而不是小数点 .
    val = val.replace(/^\./g,"");

    //保证小数点 . 只出现一次，而不能出现两次以上
    val = val.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
    //只能输入两个小数
    val = val.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');
  }
  return val
}

//只能输入正整数
export function limitIntNumber(val) {
  if(val){
    val = val.replace(/^(0+)|[^\d]+/g,'');
  }
  return val
}

//只能输入字符和数字
export function limitCharAndNumber(val) {
  if(val){
    val = val.replace(/[^a-zA-Z0-9-]/g,'');
  }
  return val
}


//数据扁平化处理
export function flattenData(data) {
  let result = [];
  for (let item of data) {
    result.push(item);
    if (item.children) {
      result = result.concat(flattenData(item.children));
    }
  }
  return result;
}

export function flattenDetailData(data) {
  let result = [];
  for (let item of data) {
    result.push(item);
    if (item.detailList && item.detailList.length>1) {
      result = result.concat(flattenData(item.detailList));
    }
  }
  return result;
}

//将单位mm转成px
export function mmToPx(mm) {
  // 创建一个隐形的div元素
  var div = document.createElement('div');
  // 设置div的宽度为指定的毫米数
  div.style.width = mm + 'mm';
  // 将div插入到文档中
  document.body.appendChild(div);
  // 获取div的像素宽度
  var px = div.offsetWidth;
  // 删除div元素
  document.body.removeChild(div);
  // 返回像素值
  return px;
}